package pri.syl.xiaowu.websocket.netty.server.handler;

import  pri.syl.xiaowu.websocket.core.template.WebsocketChannelTemplate;
import  pri.syl.xiaowu.websocket.core.template.WebsocketRouteTemplate;
import  pri.syl.xiaowu.websocket.netty.server.handler.core.factory.execution.WebsocketServerHandlerFactoryExecution;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.Getter;
import lombok.Setter;

/**
 * @Author YunLong
 * @Date 2021/7/18 19:16
 * @Description websocketServerHandler处理器
 **/
@Getter
@Setter
public class WebsocketServerHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    private WebsocketRouteTemplate websocketRouteTemplate;
    private WebsocketChannelTemplate websocketChannelTemplate;

    public WebsocketServerHandler(WebsocketRouteTemplate websocketRouteTemplate, WebsocketChannelTemplate websocketChannelTemplate) {
        this.websocketRouteTemplate = websocketRouteTemplate;
        this.websocketChannelTemplate = websocketChannelTemplate;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) {
        WebsocketServerHandlerFactoryExecution.business(websocketRouteTemplate, websocketChannelTemplate, msg);
    }

    /**
     * 超时触发
     **/
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        WebsocketServerHandlerFactoryExecution.timeoutEvent(((IdleStateEvent) evt).state(), websocketRouteTemplate, websocketChannelTemplate);
        super.userEventTriggered(ctx, evt);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        WebsocketServerHandlerFactoryExecution.closeEvent(websocketRouteTemplate, websocketChannelTemplate);
        super.channelInactive(ctx);
    }
}
